package com.spacecolony.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.spacecolony.model.Player;
import com.spacecolony.model.UserAccount;

public class OfflineGameDAO extends SQLiteOpenHelper implements IGameDAO {
	
	//
	public static final String USERACCOUNTS_TABLE = "user_accounts";
	public static final String USER_SQLITE_ID = "user_id";
	public static final String USERNAME = "username";
	public static final String EMAIL_ADDRESS = "email_address"; 
	
	public static final String PLAYERS_TABLE = "players";
	public static final String PLAYER_SQLITE_ID = "player_id";
	public static final String HP = "hp";
	public static final String DAMAGE = "damage";
	public static final String THRUSTER_CAPACITY = "thruster_capacity";
	
	/**
	 * Constructor that calls SQLiteOpenHelper constructor
	 * @param ctx - context passed from Activity layer
	 */
	public OfflineGameDAO(Context ctx){
		super(ctx, "spacecolony", null, 1);
	}
	
	/*
	 * {@inheritDoc}
	 */
	@Override
	public void updatePlayer(Player player) throws Exception {
		ContentValues cv = new ContentValues();
		cv.put(DAMAGE, player.getProjectileDamage());
		cv.put(HP, player.getHp());
		cv.put(THRUSTER_CAPACITY, player.getThrusterCapacity());
		getWritableDatabase().update(PLAYERS_TABLE, cv, PLAYER_SQLITE_ID + "=" + player.getPlayerId(), null);

	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public boolean postToFacebook(String message) {
		// TODO Auto-generated method stub
		return false;
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public UserAccount loadAccount(int sqlUserId) throws Exception {
		UserAccount user = null;
		
		//select account from SQLite DB
		String sqlSelect = "SELECT * FROM " + USERACCOUNTS_TABLE + " WHERE " + USER_SQLITE_ID + " = " + sqlUserId;
		
		// run this query.
		Cursor cursor = getReadableDatabase().rawQuery(sqlSelect, null);
		
		if (cursor.getCount() == 1){
			cursor.moveToFirst();
			user = new UserAccount();
			user.setUserId(sqlUserId);
			user.setUsername(cursor.getString(cursor.getColumnIndex(USERNAME)));
			//call loadPlayer to retrieve player from SQLite DB 
			user.setPlayer(loadPlayer(cursor.getInt(cursor.getColumnIndex(PLAYER_SQLITE_ID))));
		}
		
		return user;
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public Player loadPlayer(int playerId) throws Exception {
		Player player = null;
		
		//select player from SQLite DB
		String sqlSelect = "SELECT * FROM " + PLAYERS_TABLE + " WHERE " +  PLAYER_SQLITE_ID + " = " + playerId;
		
		// run this query.
		Cursor cursor = getReadableDatabase().rawQuery(sqlSelect, null);
			
		if (cursor.getCount() == 1){
			cursor.moveToFirst();
			player = new Player();
			player.setPlayerId(cursor.getInt(cursor.getColumnIndex(PLAYER_SQLITE_ID)));
			player.setHp(cursor.getInt(cursor.getColumnIndex(HP)));
			player.setProjectileDamage(cursor.getInt(cursor.getColumnIndex(DAMAGE)));
			player.setThrusterCapacity(cursor.getInt(cursor.getColumnIndex(THRUSTER_CAPACITY)));
		}
		
		return player;
	}
	
	/*
	 * {@inheritDoc}
	 */
	@Override
	public UserAccount saveAccount(UserAccount user) throws Exception {
		// check if Account already exists using select statement
		String sqlSelect = "SELECT * FROM " + USERACCOUNTS_TABLE + " WHERE " + USER_SQLITE_ID + " = " + user.getUserId();
		
		// run this query.
		Cursor cursor = getReadableDatabase().rawQuery(sqlSelect, null);
		
		//if user exists, update that row
		if (cursor.getCount() == 1){
			//check if player exists by seeing if the column contains a null value
			cursor.moveToFirst();
			long pSqliteId;
			if(!cursor.isNull(cursor.getColumnIndex(PLAYER_SQLITE_ID))){
				//if player exists, update player
				this.updatePlayer(user.getPlayer());
				pSqliteId = user.getPlayer().getPlayerId();
				user.getPlayer().setPlayerId((int) pSqliteId);
			}
			else{
				//if player doesn't exist, create player
				ContentValues pCv = new ContentValues();
				pCv.put(HP, user.getPlayer().getHp());
				pCv.put(DAMAGE, user.getPlayer().getProjectileDamage());
				pCv.put(THRUSTER_CAPACITY, user.getPlayer().getThrusterCapacity());
				
				// insert the data to DB
				pSqliteId = getWritableDatabase().insert(PLAYERS_TABLE, null, pCv);
			}
			//update useraccount
			ContentValues uCv = new ContentValues();
			uCv.put(USERNAME, user.getUsername());
			uCv.put(EMAIL_ADDRESS, user.getEmailAddress());
			uCv.put(PLAYER_SQLITE_ID, pSqliteId);
			
			getWritableDatabase().update(USERACCOUNTS_TABLE, uCv, USER_SQLITE_ID + "=" + user.getUserId(), null);
		}
		//if user doesn't exist, create user
		else{
			//insert new player row to generate player id
			ContentValues pCv = new ContentValues();
			pCv.put(HP, user.getPlayer().getHp());
			pCv.put(DAMAGE, user.getPlayer().getProjectileDamage());
			pCv.put(THRUSTER_CAPACITY, user.getPlayer().getThrusterCapacity());
			
			// insert the data to DB
			long pSqliteId = getWritableDatabase().insert(PLAYERS_TABLE, null, pCv);
			user.getPlayer().setPlayerId((int)pSqliteId);
			//add new user row
			ContentValues uCv = new ContentValues();
			uCv.put(USERNAME, user.getUsername());
			uCv.put(EMAIL_ADDRESS, user.getEmailAddress());
			uCv.put(PLAYER_SQLITE_ID, pSqliteId);
			
			// insert the data
			long uSqliteId = getWritableDatabase().insert(USERACCOUNTS_TABLE, null, uCv);
			user.setUserId((int)uSqliteId);
			
		}
		return user;
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		String schema = "CREATE TABLE " + USERACCOUNTS_TABLE + " (" + USER_SQLITE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + USERNAME + " INTEGER, " + EMAIL_ADDRESS + " TEXT, " + PLAYER_SQLITE_ID + " INTEGER ); CREATE TABLE " + PLAYERS_TABLE + " ( " + PLAYER_SQLITE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + HP + " INTEGER, " + DAMAGE + " INTEGER, " + THRUSTER_CAPACITY + " INTEGER );";
		schema.length();
		db.execSQL(schema);
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
		//Called when need to update the version of a SQLite DB. No plan to NEED to implement this 
		
	}

	

}
